#!/bin/sh

on_exit() {
	mountpoint -q /proc && umount /proc
	exec /sbin/init "$*"
}

trap on_exit EXIT

mount -t proc proc /proc || exit 1
grep -q overlay /proc/filesystems || exit 1

if ! grep -q 'root=.*nfs\|mmcblk\|ram' /proc/cmdline; then
	if grep -q ubifs /proc/cmdline; then
		mount -t ubifs ubi0:rootfs_data /overlay
	else
		mtdblkdev=$(awk -F ':' '/rootfs_data/ {print $1}' /proc/mtd | sed 's/mtd/mtdblock/')
		mtdchrdev=$(grep 'rootfs_data' /proc/mtd | cut -d: -f1)
		if ! mount -t jffs2 /dev/$mtdblkdev /overlay || dmesg | grep -q "jffs2.*: Magic bitmask.*not found"; then
			mountpoint -q /overlay && umount /overlay
			echo "Formatting flash..."
			grep -q 'nand' /proc/cmdline || jffs2="-j"
			flash_eraseall $jffs2 /dev/$mtdchrdev
			if ! mount -t jffs2 /dev/$mtdblkdev /overlay && ! mount -t tmpfs tmpfs /overlay; then
				echo "Cannot mount overlay."
				exit 1
			fi
		fi
	fi

	if grep -q overlayfs /proc/filesystems; then
		if ! mount -t overlayfs overlayfs -o lowerdir=/,upperdir=/overlay,ro /mnt; then
			umount /overlay
			exit 1
		fi
	else
		overlay_rootdir=/overlay/root
		overlay_workdir=/overlay/work
		mkdir -p $overlay_rootdir $overlay_workdir
		if ! mount -t overlay overlay -o lowerdir=/,upperdir=$overlay_rootdir,workdir=$overlay_workdir /mnt; then
			umount /overlay
			exit 1
		fi
	fi

	pivot_root /mnt /mnt/rom
	mount -o noatime,move /rom/proc /proc
	mount -o noatime,move /rom/dev /dev
	mount -o noatime,move /rom/overlay /overlay
fi
